﻿#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include "model.h"

Model::Model(const char *filename) : verts_(), facesV_() {
    std::ifstream in;
    in.open (filename, std::ifstream::in);
    if (in.fail()) return;
    std::string line;
    while (!in.eof()) {
        std::getline(in, line);
        std::istringstream iss(line.c_str());
        char trash;
        if (!line.compare(0, 2, "v ")) {
            iss >> trash;
            Vec3f v;
            for (int i=0;i<3;i++) iss >> v.raw[i];
            verts_.push_back(v);
        } else if (!line.compare(0, 2, "f ")) {
            std::vector<int> f_v;
            std::vector<int> f_vt;
            std::vector<int> f_vn;
            int itrash, vIdx, vtIdx, vnIdx;
            iss >> trash;
            while (iss >> vIdx >> trash >> vtIdx >> trash >> vnIdx) {
                vIdx--; // in wavefront obj all indices start at 1, not zero
                vtIdx--;
                vnIdx--;
                f_v.push_back(vIdx);
                f_vt.push_back(vtIdx);
                f_vn.push_back(vnIdx);
            }
            facesV_.push_back(f_v);
            facesVT_.push_back(f_vt);
            facesVN_.push_back(f_vn);
        }
        else if (!line.compare(0, 4, "vt  "))
        {
			iss >> trash;
            iss >> trash;
			Vec3f v;
			for (int i = 0;i < 3;i++) iss >> v.raw[i];
            vertsTexture_.emplace_back(v[0], v[1]);
        }
		else if (!line.compare(0, 4, "vn  "))
		{
			iss >> trash;
			iss >> trash;
			Vec3f v;
			for (int i = 0;i < 3;i++) iss >> v.raw[i];
            vertsNormal_.push_back(v);
		}
    }
    std::cerr << "# v# " << verts_.size() << " f# "  << facesV_.size()  << " vt# " << vertsTexture_.size() << std::endl;
}

Model::~Model() {
}

int Model::nverts() {
    return (int)verts_.size();
}

int Model::nfaces() {
    return (int)facesV_.size();
}

std::vector<int> Model::face_v(int idx) {
    return facesV_[idx];
}

std::vector<int> Model::face_vt(int idx)
{
    return facesVT_[idx];
}

std::vector<int> Model::face_vn(int idx)
{
    return facesVN_[idx];
}

Vec3f Model::vert(int i) {
    return verts_[i];
}

Vec2f Model::vertTexture(int i)
{
    return vertsTexture_[i];
}

Vec3f Model::vertNormal(int i)
{
    return vertsNormal_[i];
}

